<?php

namespace App\Http\Controllers\System;


use App\Events\Event;
use App\Events\ExampleEvent;
use App\Events\StudentEvent;
use App\Events\TeacherEvent;
use App\Model\Business\Demoment;
use App\Model\Foundation\CourseType;
use App\Model\Foundation\TeacherCourseType;
use App\Model\System\NoticeConfig;
use App\Model\System\SystemConfig;
use App\Model\System\User;
use Carbon\Carbon;
use App\Model\System\Token;
use App\Model\Business\Appointment;
use App\Model\Foundation\Student;
use App\Model\Foundation\Teacher;
use App\Model\System\Eeofile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use Laravel\Lumen\Routing\Controller as BaseController;

use App\Http\Controllers\MessagePacket;
use Mockery\CountValidator\Exception;


class ExcelController extends BaseController
{
    use MessagePacket;

    const  FILEFILED = 'Filedata';


    function getFile()
    {
        var_dump('star ');
        event(new ExampleEvent('hallo excel'));
        var_dump('form excel ');
    }


    /**
     * 上传文件
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    function loadFromFile(Request $request)
    {
        if(!$request->has('importer')){
            return $this->fail(false, '参数错误:缺少importer');
        }
        try{
            $file = $this->uploadFile($request);
            $excelRows = $this->parseExcel($file);
            if(empty($excelRows)){
                throw  new \Exception('上传内容为空');
            }
            $importer = $request->get('importer');
            $result = $this->$importer($excelRows);
            return  $this->success($result);
        }catch (Exception $e){
            return $this->fail(false, $e->getMessage());
        }

    }


    /**
     * 解析Excel文件
     * @param $filePath
     * @return array
     */
    function parseExcel($filePath)
    {
        $reader = app('excel')->load($filePath);
        $rows = $reader->toArray();
        return $rows;
    }


    /**
     * 上传Excel
     * @param Request $request
     * @return string
     */
    function uploadFile(Request $request)
    {
        $file = $request->file(self::FILEFILED);
        $move2path = Eeofile::makeUploadPath($file);
        $existedFile = Eeofile::getUploadFileFullName($file);
        if(file_exists($existedFile)){
            # todo 取指纹判断重复
            $fileName = $existedFile;
        }else{
            $target = $file->move($move2path, $file->getClientOriginalName());
            $fileName =  $target->getRealPath();
        }
        return $fileName;
    }


    /**
     * 批量导入学生
     * @param $rows
     * @return array
     * @throws \Exception
     */
    function student($rows)
    {
       try{
           //报错数组
           $error = [];
           foreach($rows as $k=>$row){

               //初始化报错信息
               $errorinfo['student'] = $row;
               $errorinfo['errno'] = 0;
               $errorinfo['error'] = "缺少必填项";

               $fields = [];
               foreach($row as $key=>$val){
                   $fields[$key] = $row[$key];
               }
               if(empty($row['classinno']) || empty($row['name']) || empty($row['mobile'])){
                   $errorinfo['errno'] = 1;
                   $errorinfo['error'] = "缺少必填项";
                   $error[$k] = $errorinfo;
                   continue;
               }
               $fields['ClassInNo'] = $row['classinno'];
               $date = $row['birthday'];
               if(is_string($date)){
                   $date = str_replace('/',"-",$date);
                   $row['birthday'] = new Carbon($date);
               }
               if(!empty($row['birthday'])){
                   $fields['birthday'] = $row['birthday']->toDateTimeString();
               }

               # 排重
               $student = Student::where('ClassInNo', $row['classinno'])->first();
               if($student){
                   $errorinfo['errno'] = 1;
                   $errorinfo['error'] = "该学生的ClassIn账号已存在";
                   $error[$k] = $errorinfo;
                   continue;
               }else{
                   # 创建学生
                   $student = new Student($fields);
                   $student->save();
                   try{
                       $this->dispatchStudentEvent($student, Event::CREATE,$fields['password']);
                   }catch (\Exception $e){
                       $student->delete();
                       $errorinfo['errno'] = 1;
                       $errorinfo['error'] = "同步EEO失败".$e->getMessage();
                       $error[$k] = $errorinfo;
                       continue;
                   }
               }
               # 关联用户表
               $user = User::where('number',$fields['mobile'])->first();
               if(empty($user)) {
                   $obj = new User();
                   $obj->userid = User::generateID();
                   $obj->type = User::STUDENT;
                   $obj->email = $fields['email'];
                   $obj->number = $fields['mobile'];
                   $obj->islock = User::UNLOCK;
                   $password = '123456';
                   $config = SystemConfig::find(1);
                   if($config){
                       $password = $config->defaultpassword;
                   }
                   $obj->setSecurityCode($password);
                   $obj->updateCreator();
                   $student->userid = $obj->userid;
                   $obj->save();
               }
               else {
                   $student->userid = $user->userid;
               }
               $student->save();
               #新建提醒  默认开启微信及邮件通知，课前60分钟提醒，每天12点提醒。
               $obj = new NoticeConfig([
                   'utype'=>2,
                   'uid'=>$student->studentuid,
                   'ntype'=>1,
                   'byemail'=>1,
                   'bywechat'=>1,
                   'ahead'=>60,
                   'perday'=>12]);
               $obj->save();
               $obj2 = new NoticeConfig(['utype'=>2, 'uid'=>$student->studentuid, 'ntype'=>2]);
               $obj2->save();

           }
           if($error){
               return $error;
           }else{
               return true;
           }
       }catch (\Exception $e){
           return $this->fail(false,'导入失败',$e->getMessage());

       }
    }

    /**
     * 导入教师
     * @param $rows
     * @return bool
     * @throws \Exception
     */
    function teacher($rows)
    {
	try{
	    //报错数组
            $error = [];
            foreach($rows as $k=>$row){

                //初始化报错信息
                $errorinfo['student'] = $row;
                $errorinfo['errno'] = 0;
                $errorinfo['error'] = "缺少必填项";

                $fields = [];
                foreach($row as $key=>$val){
                    $fields[$key] = $row[$key];
                }
                if(empty($row['classinno']) || empty($row['name']) || empty($row['mobile'])){
                    $errorinfo['errno'] = 1;
                    $errorinfo['error'] = "缺少必填项";
                    $error[$k] = $errorinfo;
                    continue;
                }
                $coursetypes = explode(',',$fields['coursetypes']);
                $id = CourseType::whereIn('coursetypename',$coursetypes)
                        ->pluck('coursetypeuid');
                $typeIds = $id;

                unset($fields['coursetypes']);

                $fields['lastname'] = $row['name'];
                $fields['ClassInNo'] = $row['classinno'];
                $fields['sex'] = strtolower($row['sex'])=='m' ? 0 : 1;


                # 排重
                $teacher = Teacher::where('ClassInNo', $row['classinno'])->first();
                if($teacher){
                    $errorinfo['errno'] = 1;
                    $errorinfo['error'] = "该老师的ClassIn账号已存在";
                    $error[$k] = $errorinfo;
                    continue;
                }else {
                    # 创建教师
                    $teacher = new Teacher($fields);
//                    $teacher->created_by = Token::user()->userid;
                    $teacher->save();
                    #更新教师_课程类型表
                    if (!empty($typeIds)) {
                        $teacherid = $teacher->teacheruid;
                        foreach ($typeIds as $typeId) {
                            $courses= new TeacherCourseType(
                                ['teacheruid' => $teacherid,
                                    'coursetypeid' => $typeId]);
                            $courses->save();
                        }
                    }
                    try {
                        $this->dispatchTeacherEvent($teacher, Event::CREATE, $fields['password']);
                    } catch (\Exception $e) {
                        $teacher->delete();
                        $errorinfo['errno'] = 1;
                        $errorinfo['error'] = "同步EEO失败" . $e->getMessage();
                        $error[$k] = $errorinfo;
                        continue;
                    }
                }
                # 关联用户表
                $user = User::where('number',$fields['mobile'])->first();
                if(empty($user)) {
                    $obj = new User();
                    $obj->userid = User::generateID();
                    $obj->type = User::TEACHER;
                    $obj->email = $fields['email'];
                    $obj->number = $fields['mobile'];
                    $obj->islock = User::UNLOCK;
                    $password = '123456';
                    $config = SystemConfig::find(1);
                    if($config){
                        $password = $config->defaultpassword;
                    }
                    $obj->setSecurityCode($password);
                    $obj->updateCreator();
                    $teacher->userid = $obj->userid;
                    $obj->save();
                }
                else {
                    $teacher->userid = $user->userid;
                }
                #保存成功
                $teacher->save();

                #新建提醒  默认开启微信及邮件通知，课前60分钟提醒，每天12点提醒。
                $obj = new NoticeConfig([
                    'utype'=>1,
                    'uid'=>$teacher->teacheruid,
                    'ntype'=>1,
                    'byemail'=>1,
                    'bywechat'=>1,
                    'ahead'=>60,
                    'perday'=>12]);
                $obj->save();
                $obj2 = new NoticeConfig(['utype'=>1, 'uid'=>$teacher->teacheruid, 'ntype'=>2]);
                $obj2->save();
            }
            if($error){
                return $error;
            }else{
                return true;
            }
        }catch (\Exception $e){
            return $this->fail(false,'导入失败',$e->getMessage());
        }
    }

    /**
     * 试听课导入
     * @param $rows
     * @return bool
     * @throws \Exception
     */
    function demo($rows)
    {
        try{
	    //报错数组
            $error = [];
            foreach($rows as $k=>$row){
                //初始化报错信息
                $errorinfo['student'] = $row;
                $errorinfo['errno'] = 0;
                $errorinfo['error'] = "缺少必填项";

                $fields = [];
                foreach($row as $key=>$val){
                    $fields[$key] = $row[$key];
                }
                if(empty($row['classinno']) || empty($row['chinesename'] || empty($row['mobile']))){
                    $errorinfo['errno'] = 1;
                    $errorinfo['error'] = "缺少必填项";
                    $error[$k] = $errorinfo;
                    continue;
                }
                $fields['status'] = 0;
                $fields['ClassInNo'] = $row['classinno'];
                $fields['sex'] = strtolower($row['sex'])=='m' ? 0 : 1;
                $date = $row['dateofbirth'];
                if(is_string($date)){
                    $date = str_replace('/',"-",$date);
                    $row['dateofbirth'] = new Carbon($date);
                }
                if(!empty($row['dateofbirth'])){
                    $fields['dateofbirth'] = $row['dateofbirth']->toDateTimeString();
                }

                # 创建
                $demoment = new Demoment($fields);
                $demoment->created_by = Token::user()->userid;
                $demoment->updated_by = Token::user()->userid;
                $demoment->save();
                # 排重
                $student = Student::where('ClassInNo', $demoment->ClassInNo)->first();
                if($student){
                    $demoment->studentuid = $student->studentuid;
                    $demoment->save();
                }else{
                    # 同步创建学生
                    $student = New Student();
                    $student->name = $demoment->chinesename;
                    $student->ClassInNo = $demoment->ClassInNo;
                    $student->birthday = $demoment->dateofbirth;
                    $student->mobile = $demoment->mobile;
                    $student->email = $demoment->email;
                    if(!$student->save()){
                        $demoment->delete();
                        $errorinfo['errno'] = 1;
                        $errorinfo['error'] = "保存学生失败";
                        $error[$k] = $errorinfo;
                        continue;
                    }
                    $demoment->studentuid = $student->studentuid;
                    $demoment->save();
                    try{
                        $this->dispatchStudentEvent($student, Event::CREATE,$fields['password']);
                        # 关联用户表
                        $user = User::where('number',$fields['mobile'])->first();
                        if(empty($user)) {
                            $obj = new User();
                            $obj->userid = User::generateID();
                            $obj->type = User::STUDENT;
                            $obj->email = $fields['email'];
                            $obj->number = $fields['mobile'];
                            $obj->islock = User::UNLOCK;
                            $password = '123456';
                            $config = SystemConfig::find(1);
                            if($config){
                                $password = $config->defaultpassword;
                            }
                            $obj->setSecurityCode($password);
                            $obj->updateCreator();
                            $student->userid = $obj->userid;
                            $obj->save();
                        }
                        else {
                            $student->userid = $user->userid;
                        }
                        $student->save();
                        #新建提醒  默认开启微信及邮件通知，课前60分钟提醒，每天12点提醒。
                        $obj = new NoticeConfig([
                            'utype'=>2,
                            'uid'=>$student->studentuid,
                            'ntype'=>1,
                            'byemail'=>1,
                            'bywechat'=>1,
                            'ahead'=>60,
                            'perday'=>12]);
                        $obj->save();
                        $obj2 = new NoticeConfig(['utype'=>2, 'uid'=>$student->studentuid, 'ntype'=>2]);
                        $obj2->save();

                    }catch (\Exception $e){
                        $student->delete();
                        $demoment->delete();
                        $errorinfo['errno'] = 1;
                        $errorinfo['error'] = "同步EEO失败".$e->getMessage();
                        $error[$k] = $errorinfo;
                        continue;
                    }
                }
            }
            if($error){
                return $error;
            }else{
                return true;
            }
        }catch (\Exception $e){
            throw  $e;
            return $e->getMessage();
        }
    }
    /**
     * 试听课导出
     *
     */
    function export()
    {
        $datas = DB::table('demoments as demo')
            ->where('demo.status',1)
            ->join('schedules as sche','sche.scheduleid','=','demo.scheduleid')
            ->join('teachers','teachers.teacheruid','=','sche.teacheruid')
            ->select('demo.teachername','teachers.ClassInNo as teacherno','sche.name','sche.begintime','sche.endtime',
                     'sche.quotas','sche.usequotas','demo.chinesename','demo.fullname','demo.ClassInNo as studentno',
                     'demo.dateofbirth', 'demo.sex','demo.remark1','demo.remark2','demo.remark3')
            ->get();
        $cellData = [
            [
                '教师姓名',
                '教师ClassIn账号',
                '课节名称',
                '开课时间',
                '结束时间',
                '课节名额',
                '已用名额',
                '学生姓名',
                '学生英文名',
                '学生ClassIn账号',
                '年龄',
                '性别',
                '备注1',
                '备注2',
                '备注3']
        ];


        $tempdata = [];
        foreach ($datas as $data){
            $temp = [];
            foreach ($data as $key=>$value){
                if($value === '' || $value === null || $value === "0000-00-00 00:00:00"){
                    $value = 'N/A';
                }else{
                    if($key == 'dateofbirth'){
                        if($value == '0000-00-00 00:00:00'){
                            $value = 'N/A';
                        }else{
                            $date = date("Y-m-d",strtotime($value));
                            $value = $this->birthday($date);
                            if($value > 150 || $value < 1){
                                $value = 'N/A';
                            }
                        }

                    }
                    if($key == 'sex'){
                        if($value == 0){
                            $value = '男';
                        }else{
                            $value = '女';
                        }
                    }
                }
                $temp[] = $value;
            }
            $tempdata[] = $temp;
        }
        $cellData = array_merge($cellData,$tempdata);
        Excel::create('试听表'.date('Y-m-d'),function($excel) use ($cellData){
            $excel->sheet('score', function($sheet) use ($cellData){
                $sheet->rows($cellData);
            });
        })->export('xls');
    }

    // 计算生日
    function birthday($birthday){
        list($year,$month,$day,) = explode("-",$birthday);
        $year_diff = date("Y") - $year;
        $month_diff = date("m") - $month;
        $day_diff  = date("d") - $day;
        if ($day_diff < 0 || $month_diff < 0)
            $year_diff--;
        return $year_diff;
    }

    /**
     * 导入正式课预约订单
     * @param $rows
     * @return bool
     * @throws \Exception
     */
    function appoint($rows)
    {
        try{
	    //报错数组
            $error = [];
            foreach($rows as $k=>$row){
                //初始化报错信息
                $errorinfo['student'] = $row;
                $errorinfo['errno'] = 0;
                $errorinfo['error'] = "缺少必填项";

                $fields = [];
                foreach($row as $key=>$val){
                    $fields[$key] = $row[$key];
                }
                if(empty($row['studentname']) || empty($row['mobile'])){
                    $errorinfo['errno'] = 1;
                    $errorinfo['error'] = "缺少必填项";
                    $error[$k] = $errorinfo;
                    continue;
                }
                $fields['status'] = 0;
                $date = $row['date'];
                if(is_string($date)){
                    $date = str_replace('/',"-",$date);
                    $row['date'] = new Carbon($date);
                }
                if(!empty($row['date'])){
                    $fields['orderdate'] = $row['date']->toDateTimeString();
                }

                # 创建
                $appoint = new Appointment($fields);

                # 排重
                $student = Student::where('ClassInNo', $row['mobile'])->first();
                if (!$student) {
                    $errorinfo['errno'] = 1;
                    $errorinfo['error'] = "学生还未添加到学生信息表中";
                    $error[$k] = $errorinfo;
                    continue;
                }else{
                    $appoint->studentuid = $student->studentuid;
                    $appoint->creator = Token::user()->username;
                    $appoint->created_by = Token::user()->userid;
                    $appoint->updated_by = Token::user()->userid;
                    $appoint->save();
                    if (!$appoint->save()) {
                        $errorinfo['errno'] = 1;
                        $errorinfo['error'] = "保存失败";
                        $error[$k] = $errorinfo;
                        continue;
                    }
                }
            }
            if($error){
                return $error;
            }else{
                return true;
            }
        }catch (\Exception $e){
            throw  $e;
            return $e->getMessage();
        }
    }


    /**
     * 抛出学生事件
     * @param Student $student
     * @param $action
     * @return mixed
     * @throws \Exception
     */
    protected function dispatchStudentEvent(Student $student, $action,$password)
    {
        try{
            $event = new StudentEvent($student, $action,$password);
            event($event);
        }catch (\Exception $e){
            throw $e;
            return $e->getMessage();
        }
    }

    /**
     * 抛出教师事件
     * @param Teacher $teacher
     * @param $action
     * @return mixed
     * @throws \Exception
     */
    protected function dispatchTeacherEvent(Teacher $teacher, $action,$password)
    {
        try{
            $event = new TeacherEvent($action,$teacher,$password);
            event($event);
        }catch (\Exception $e){
            throw $e;
            return $e->getMessage();
        }
    }


}
